package com.jdz.filter;

import com.jdz.common.Const;
import com.jdz.common.ResponseCode;
import com.jdz.common.ServerResponse;
import com.jdz.service.IUserService;
import com.jdz.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class DownloadFileFilter implements Filter {

    @Autowired
    IUserService iUserService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String url = request.getRequestURL().toString();

        HttpSession session = request.getSession();
        UserVo userVo = (UserVo) session.getAttribute(Const.CURRENT_USER);

        if(url.indexOf("index.html")>=0&&userVo==null){
            response.sendRedirect("/Admin/admin-index.html");
        }
        if(url.indexOf("admin-index.html")>=0&&userVo==null){
            response.sendRedirect("/Admin/admin-index.html");
        }


        if(!url.contains("upload/")){
            filterChain.doFilter(request, response);
            return;
        }


        if(url.contains("upload/"+userVo.getStuno())){
            filterChain.doFilter(request, response);
            return;
        }


        if (userVo == null) {
            return;
        }
        //校验一下是否是管理员
        if (iUserService.checkAdminRole(userVo).isSuccess()) {
            //是管理员
            if (iUserService.checkPrivilege(userVo, url).isSuccess()) {
                //增加我们处理逻辑
                filterChain.doFilter(request, response);
            } else {
                return;
            }
        } else {
            return;
        }

    }

    @Override
    public void destroy() {

    }
}
